import { ICrawlerEngine } from '@weubi/engines';
import { CrawlerTask, CrawlerResult } from '@weubi/shared';
import { BaseCrawlerEngine } from '@weubi/engines';
import { logger } from '../utils/logger';

export class SeleniumEngine extends BaseCrawlerEngine implements ICrawlerEngine {
  readonly name = 'selenium' as const;
  readonly version = '1.0.0';
  readonly description = 'Selenium WebDriver-based crawler engine';

  private driver: any = null;

  constructor() {
    super();
  }

  protected async doInitialize(): Promise<void> {
    try {
      // 动态导入 selenium-webdriver，如果不存在会抛出错误
      const { Builder } = await import('selenium-webdriver');
      const chrome = await import('selenium-webdriver/chrome');
      
      const options = new chrome.Options();
      options.addArguments('--headless');
      options.addArguments('--no-sandbox');
      options.addArguments('--disable-setuid-sandbox');

      this.driver = await new Builder()
        .forBrowser('chrome')
        .setChromeOptions(options)
        .build();
        
      logger.info('✅ Selenium engine initialized');
    } catch (error) {
      logger.error('❌ Failed to initialize Selenium engine:', error);
      throw error;
    }
  }

  protected async doExecute(task: CrawlerTask): Promise<CrawlerResult> {
    if (!this.driver) {
      throw new Error('Selenium engine not initialized');
    }

    const startTime = Date.now();

    try {
      // 设置超时
      await this.driver.manage().setTimeouts({
        implicit: task.config.timeout || 30000,
        pageLoad: task.config.timeout || 30000
      });

      // 导航到目标URL
      await this.driver.get(task.url);

      // 执行自定义脚本（如果有）
      let data: any = {};
      if (task.config.script) {
        data = await this.driver.executeScript(task.config.script);
      } else if (task.config.selectors) {
        // 使用选择器提取数据
        const { By } = await import('selenium-webdriver');
        for (const [key, selector] of Object.entries(task.config.selectors)) {
          if (typeof selector === 'string') {
            try {
              const element = await this.driver.findElement(By.css(selector));
              data[key] = await element.getText();
            } catch (error) {
              // 元素未找到，跳过
              data[key] = null;
            }
          }
        }
      } else {
        // 默认获取页面内容
        data = {
          title: await this.driver.getTitle(),
          content: await this.driver.getPageSource()
        };
      }

      const duration = Date.now() - startTime;

      return {
        success: true,
        data,
        metadata: {
          engine: 'selenium',
          timestamp: new Date(),
          url: task.url,
          duration,
          statusCode: 200 // Selenium 不直接提供状态码
        }
      };

    } catch (error) {
      const duration = Date.now() - startTime;
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';

      return {
        success: false,
        error: errorMessage,
        metadata: {
          engine: 'selenium',
          timestamp: new Date(),
          url: task.url,
          duration
        }
      };
    }
  }

  async isAvailable(): Promise<boolean> {
    try {
      await import('selenium-webdriver');
      return true;
    } catch {
      return false;
    }
  }

  protected async doCleanup(): Promise<void> {
    if (this.driver) {
      await this.driver.quit();
      this.driver = null;
      logger.info('✅ Selenium engine cleaned up');
    }
  }

  getConfig() {
    return {
      capabilities: {
        javascript: true,
        cookies: true,
        screenshots: true,
        pdf: false,
        proxy: true,
        userAgent: true,
        headers: false,
      },
      defaults: {
        timeout: 30000,
        retries: 3,
        delay: 1000,
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      },
      limits: {
        maxConcurrency: 3,
        maxMemory: 256 * 1024 * 1024, // 256MB
        maxTimeout: 300000,
      },
    };
  }
}
